package com.xingfly.web;

import com.xingfly.model.vo.EmailVo;
import com.xingfly.service.CaptchaService;
import com.xingfly.service.MailService;
import com.xingfly.util.CaptchaUtil;
import com.xingfly.util.MailUtil;
import com.xingfly.web.model.ResponseModel;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * Created by SuperS on 05/01/2017.
 */
@RestController
@RequestMapping("mails")
public class MailController {
    @Autowired
    private CaptchaUtil captchaUtil;
    @Autowired
    private MailService mailService;
    @Autowired
    private CaptchaService captchaService;


    /**
     * 激活账户
     */
    @PostMapping
    @Transactional
    public ResponseModel<?> sendActiveMail(@RequestBody EmailVo email, HttpServletRequest request) {
        if (StringUtils.isEmpty(email)) {
            return ResponseModel.error(HttpStatus.BAD_REQUEST, "email不能为空!");
        }
        if (!MailUtil.emailFormat(email.getEmail())) {
            return ResponseModel.error(HttpStatus.BAD_REQUEST, "邮箱格式错误!");
        }
        String ip = MailUtil.getIpAddress(request);

        if (!mailService.isInList(MailService.ACCOUNT_KEY, ip)) {
            String captcha = captchaUtil.randomCaptcha();
            captchaService.create(CaptchaService.KEY_ACCOUNT, email.getEmail(), captcha);
            mailService.sendAccountActivationEmail(email.getEmail(), captcha);
            mailService.addIpToList(MailService.ACCOUNT_KEY, ip);
        } else {
            return ResponseModel.error(HttpStatus.BAD_REQUEST, "邮件已经发送,60秒后点击按钮重发邮件!");
        }
        return ResponseModel.create(null, HttpStatus.OK, "邮件发送成功,请注意查收!");
    }

    /**
     * 重置密码
     */
    @PutMapping
    @Transactional
    public ResponseModel<?> sendRestPassWordMail(@RequestBody EmailVo email, HttpServletRequest request) {
        if (StringUtils.isEmpty(email)) {
            return ResponseModel.error(HttpStatus.BAD_REQUEST, "email不能为空!");
        }
        if (!MailUtil.emailFormat(email.getEmail())) {
            return ResponseModel.error(HttpStatus.BAD_REQUEST, "邮箱格式错误!");
        }
        String ip = MailUtil.getIpAddress(request);
        if (!mailService.isInList(MailService.REST_KEY, ip)) {
            String captcha = captchaUtil.randomCaptcha();
            captchaService.create(CaptchaService.KEY_RESET, email.getEmail(), captcha);
            mailService.sendResetPwdEmail(email.getEmail(), captcha);
            mailService.addIpToList(MailService.REST_KEY, ip);
        } else {
            return ResponseModel.error(HttpStatus.BAD_REQUEST, "邮件已经发送,60秒后点击按钮重发邮件!");
        }
        return ResponseModel.create(null, HttpStatus.OK, "邮件发送成功,请注意查收!");
    }
}
